package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavors(dishDto);
        // 删除缓存数据
        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_1");
        return R.success("保存菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page> page(int page, int pageSize, String name) {

        //一. 菜品基础分页查询
        //1. 分页构建器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //2. 条件构建器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        //3. 查询
        dishService.page(dishPage, lqw);

        // 二. 处理分页集合数据
        Page<DishDto> dishDtoPage = new Page<>();
        // 1. 复制分页信息(排除分页集合数据. 数据不对(没有分类名称))
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //2. 单独出来集合数据
        //2.1 获取原始dishPage分页对象中集合数据
        List<Dish> records = dishPage.getRecords();

        List<DishDto> dtoList = new ArrayList<>();
        //2.2 遍历集合
        records.forEach(dish -> {
            // 创建一个DishDto对象
            DishDto dishDto = new DishDto();
            // 复制dish数据到dishDto
            BeanUtils.copyProperties(dish, dishDto);
            // 查询分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            // 设置分类名称到dishDto中
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            dtoList.add(dishDto);
        });

        // 将处理后的集合, 添加到分页对象
        dishDtoPage.setRecords(dtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 查询菜品和口味数据
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavors(id);
        return R.success(dishDto);
    }


    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavors(dishDto);

        //清楚缓存方式
        // 1. 全局清理 dish_*
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //2. 精准清理
        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_1");

        return R.success("修改菜品成功");
    }

    /**
     * 根据条件查询菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish) {
        //1) 查询redis缓存
        String key = "dish_" + dish.getCategoryId() + "_1";
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //2) 判断缓存是否有数据
        //① 若有, 直接返回缓存数据
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        //② 若无, 查询数据库

        //1. 查询菜品集合
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        // 2.复制Dosh --> DishDto
        List<DishDto> dtoList = new ArrayList<>();
        list.forEach(d -> {
            //2.1 创建一个DishDto对象
            DishDto dishDto = new DishDto();

            //2.2  复制dish数据到dishDto
            BeanUtils.copyProperties(d, dishDto);

            //2.3 查询菜品口味数据
            LambdaQueryWrapper<DishFlavor> laq = new LambdaQueryWrapper<>();
            laq.eq(DishFlavor::getDishId, d.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(laq);
            dishDto.setFlavors(flavorList);  // 设置菜品口味
            // 将dto添加到集合中
            dtoList.add(dishDto);
        });

        // 将查询的数据, 放入缓存
        redisTemplate.opsForValue().set(key, dtoList, 60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }


}
